﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace VitCode.Castle.Helper
{
    public class CsvOutputHelper
    {
        /// <summary>
        /// 生成CSV格式檔
        /// </summary>
        /// <param name="dataFilePath">檔存放路徑</param>
        /// <param name="sourceData">資料源</param>
        /// <returns>生成的檔路徑</returns>
        public string GenerateDataFile(string dataFilePath,DataTable sourceData)
        {
            string tempFileName;
            try
            {
                tempFileName = Path.GetTempFileName();
                FileInfo fi = new FileInfo(tempFileName);
                tempFileName = fi.Name.Replace(fi.Extension, ".csv");
            }
            catch
            {
                DateTime dt = DateTime.Now;
                tempFileName = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + ".csv";
            }
            StreamWriter writer = new StreamWriter(dataFilePath + "\\" + tempFileName, false, System.Text.Encoding.Default);
            writer.Write(sourceData);
            writer.Flush();
            writer.Close();
            return dataFilePath + "\\" + tempFileName;
        }
    }
}
